import React, { useState, useEffect } from 'react'
import { Card } from '&/appComponents/Antd'
import { Flex, Radio } from 'antd'
import Echarts from '&/baseUI/EChartsUI'
import dayjs from 'dayjs'
import './index.scss'

const BarChart = ({ data }) => {
  // 定义 state 变量
  const [option, setOption] = useState()
  const [xData, setXdata] = useState([])
  const options = {
    yAxis: {},
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    }
  }
  // 在 data 变量变化时执行的效果
  useEffect(() => {
    if (!data) return
    let { label, value } = data.un_flow_avg.avg_time_graph
    let xData = data.time_list.map((i) => dayjs(i).format('MM月DD日'))
    setXdata(xData)
    handlerChart(label, xData, value)
  }, [data])

  const onChange = (e) => {
    let res, t, l
    let { un_flow_avg, un_flow_cumulative, un_flow_enter_counts, flow_rates } =
      data
    if (e == 1) {
      t = true
      res = un_flow_avg.avg_time_graph.label
      l = un_flow_avg.avg_time_graph.value
    }
    if (e == 2) {
      t = true
      res = un_flow_cumulative.enterprises_timeline_graph[0].value
      l = un_flow_cumulative.enterprises_timeline_graph[0].label
    }
    if (e == 3) {
      t = false
      res = handlerData(un_flow_enter_counts.enterprises_timeline_graph)
    }
    if (e == 4) {
      t = false
      res = handlerData(flow_rates.rates_timeline_graph)
    }
    handlerChart(res, t, l, e)
  }

  const handlerChart = (sData, t, l, e) => {
    setOption({
      ...options,
      xAxis: {
        data: xData
      },
      series: [
        {
          type: 'bar',
          data: sData,
          label: {
            show: true,
            formatter: (i) => {
              if (t) {
                return l[i.dataIndex]
              } else {
                return e == 4 ? i.value + '%' : i.value
              }
            }
          }
        }
      ]
    })
  }

  const handlerData = (v) => v.map((i) => i)

  return (
    <>
      <Flex vertical gap="middle">
        <Radio.Group
          onChange={(e) => onChange(e.target.value)}
          defaultValue={1}
          buttonStyle="solid"
        >
          <Radio.Button value={1}>未落实企业平均时长</Radio.Button>
          <Radio.Button value={2}>未落实累计时长</Radio.Button>
          <Radio.Button value={3}>未落实企业数</Radio.Button>
          <Radio.Button value={4}>落实率</Radio.Button>
        </Radio.Group>
      </Flex>
      <Echarts option={option} />
    </>
  )
}

export default BarChart
